package net.lab1024.sa.base.module.support.minio;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import net.lab1024.sa.base.common.util.SmartDateFormatterEnum;
import net.lab1024.sa.base.common.util.SmartLocalDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MinioService {

    @Autowired
    private MinioClient minioClient;
    @Value("${file.storage.minio.bucket}")
    String bucket;

    public String writeData(String shopData, String historyId, String tmpPath) {
        if (StringUtils.isNoneBlank(shopData)) {
            String path = SmartLocalDateUtil.format(LocalDateTime.now(), SmartDateFormatterEnum.YMD).replaceAll("-","_") + "_" + historyId + ".json";
            if (StringUtils.isNoneBlank(tmpPath)) {
                path = tmpPath;
            }
            return uploadFile(path, shopData);
        }
        return "";
    }

    public String readData(String path) {
        return getObject(path);
    }


    /**
     * 获取文件流
     *
     * @param objectName 文件名
     * @return 二进制流
     */
    private String getObject(String objectName) {
        if (StringUtils.isBlank(objectName)) {
            return "[]";
        }
        try {
            InputStream inputStream =
                    minioClient.getObject(GetObjectArgs.builder()
                            .bucket(bucket)
                            .object(objectName)
                            .build()
                    );
            return convert(inputStream);
        } catch (Exception e) {
            // e.printStackTrace();
        }
        return "[]";
    }

    private String convert(InputStream inputStream) throws IOException {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = buffer.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        String data = stringBuilder.toString();
        if (StringUtils.isBlank(data)) {
            return "[]";
        }
        return JsonCompressor.decompress(data);
    }

    /**
     * 通过流上传文件
     *
     * @param objectName  文件对象
     * @param data 文件内容
     */
    private String uploadFile(String objectName, String data) {
        try {
            data=JsonCompressor.compress(data.replaceAll("\\s+", ""));
            ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
            return minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucket)
                            .object(objectName)
                            .stream(inputStream, inputStream.available(), -1)
                            .build()).object();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
